<?php
/**
 * tinymvc超轻量级PHP开发框架
 *
 * @author    Lansn
 * @copyright Copyright (c) 2024-2025
 * @license   tinymvc 遵循Apache2开源协议发布，需保留开发者信息。
 * @link      http://173654757.xyz
 */

namespace tinymvc\core;

use Flight;

class Lang
{
    protected static string $language = 'zh_cn';
    protected static array $data = [];
    protected static bool $initialized = false;
    protected static string $currentModule = '';

    public static function init(string $module): void
    {
        // 如果已经初始化且模块未改变，则直接返回
        if (self::$initialized && self::$currentModule === $module) {
            return;
        }
        
        self::$currentModule = $module;
        self::$initialized = true;

        $config = config('app');
        $default = $config['locale'] ?? 'zh_cn';

        // 首先检查用户session中的语言设置
        $sessionLang = null;
        if (Flight::session()) {
            $sessionLang = Flight::session()->get('language');
        }

        if ($sessionLang && in_array($sessionLang, $config['locales'] ?? [])) {
            // 使用session中保存的语言设置
            self::$language = $sessionLang;
        } else {
            // 检测浏览器语言
            $browserLang = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '', 0, 5));
            $langMap = [
                'zh-cn' => 'zh_cn',
                'zh_cn' => 'zh_cn',
                'en-us' => 'en_us',
                'en_us' => 'en_us'
            ];
            $chosenLang = $langMap[$browserLang] ?? $default;
            self::$language = in_array($chosenLang, $config['locales'] ?? []) ? $chosenLang : $default;
        }

        // 使用 Flight 缓存语言数据，key 带模块名防止跨模块污染
        $cacheKey = "lang.{$module}." . self::$language;
        $cachedData = Flight::get($cacheKey);

        if (is_array($cachedData)) {
            self::$data = $cachedData;
            return;
        }

        // 加载基础语言文件
        $baseLangFile = CFG_PATH . "language/" . self::$language . '.php';
        $baseData = [];
        if (file_exists($baseLangFile)) {
            $baseData = include $baseLangFile;
        }

        // 加载模块语言文件
        $moduleLangFile = APP_PATH . "$module/language/" . self::$language . '.php';
        $moduleData = [];
        if (file_exists($moduleLangFile)) {
            $moduleData = include $moduleLangFile;
        }

        // 合并语言文件，模块特定语言文件优先
        self::$data = array_merge($baseData, $moduleData);
        Flight::set($cacheKey, self::$data);
    }

    public static function get(string $key, $default = ''): string
    {
        return self::$data[$key] ?? $default;
    }

    public static function all(): array
    {
        return self::$data;
    }

    public static function current(): string
    {
        return self::$language;
    }
    
    /**
     * 设置并保存用户语言选择到session
     */
    public static function setLanguage(string $language): void
    {
        self::$language = $language;
        if (Flight::session()) {
            Flight::session()->set('language', $language);
        }
        // 重置初始化状态，以便重新加载语言数据
        self::$initialized = false;
    }
}